const jwt = require("jsonwebtoken"); //引入插件，生成和校验token
/**
 * Token的生成与校验
 */
let secret = "malin";

function create(data, expiresIn = 60 * 60 * 24 * 7) {
  //60 * 60 * 24 * 7 代表7天
  let token = jwt.sign({ data }, secret, {
    expiresIn,
  });
  return token;
}

//加密：生成token
// let token = create("123456");
// console.log(token); //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiMTIzNDU2IiwiaWF0IjoxNTk5MTkwODg4LCJleHAiOjE1OTk3OTU2ODh9.bVx91IPlGAP1oxBi1DUJAqCaTmPOUuWJSrmzkciAplQ

function verify(token) {
  let res;
  try {
    let result = jwt.verify(token, secret);
    console.log("token校验：", result);
    res = true;
  } catch (err) {
    res = false;
  }

  return res;
}

// let res = verify(
//   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiMTIzNDU2IiwiaWF0IjoxNTk5MTkxMDY2LCJleHAiOjE1OTkxOTEwOTZ9.siNA-8N458Bx7hqV4mCMGwu4_k2a8K7rInisxc5DAgA"
// );
// console.log(res, "校验token");

module.exports = {
  create,
  verify,
};
